package main.bytedance.permutation;

import java.util.*;

/**
 * 使用滑动窗口：
 * 把26个字符使用-‘a’,来对应到不同的位置，比如：a-‘a’ = 0 ,意思是a出现的个数就是0
 * 所以使用s1来作为滑动窗口的大小。依次往右进行匹配s1的长度开始，来匹配每个字符出现的个数
 * 这样拿到之后再s1 去比较每个字符出现的个数即可
 * @author kejl
 * @version test
 * @date 2020/5/27 8:29
 */
public class Test {
    public static void main(String[] args) {


      boolean result =  new   Test().checkInclusion("bac","abcd");
      System.out.println(result);


    }

    public boolean checkInclusion(String s1, String s2) {
        if (s1.length() > s2.length())
            return false;
        int[] s1map = new int[26];
        int[] s2map = new int[26];
        for (int i = 0; i < s1.length(); i++) {
            s1map[s1.charAt(i) - 'a']++;
            s2map[s2.charAt(i) - 'a']++;
        }
        for (int i = 0; i < s2.length() - s1.length(); i++) {
            if (matches(s1map, s2map))
                return true;
            s2map[s2.charAt(i + s1.length()) - 'a']++;
            s2map[s2.charAt(i) - 'a']--;
        }
        return matches(s1map, s2map);
    }
    public boolean matches(int[] s1map, int[] s2map) {
        for (int i = 0; i < 26; i++) {
            if (s1map[i] != s2map[i])
                return false;
        }
        return true;
    }

}
